<template>
	<SearchForm v-model:query-params="search" :config="searchConfig" @search="onSearch" @reset="reset" />
	<el-button plain type="primary" @click="addRole">新增</el-button>
	<el-table border :data="allRole" class="m-t-10px">
		<el-table-column type="index" align="center" label="#"></el-table-column>
		<el-table-column label="ID" align="center" prop="id"></el-table-column>
		<el-table-column label="角色名称" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
		<el-table-column label="创建世间" align="center" show-overflow-tooltip prop="createTime"></el-table-column>
		<el-table-column label="更新时间" align="center" show-overflow-tooltip prop="updateTime"></el-table-column>
		<el-table-column label="操作" align="center">
			<!-- row:已有的角色对象 -->
			<template #default="{ row }">
				<el-button link type="primary" @click="setPermisstion(row)">分配权限</el-button>
				<el-button link type="primary" @click="updateRole(row)">编辑</el-button>
				<el-popconfirm :title="`你确定要删除${row.roleName}?`" @confirm="removeRole(row.id)">
					<template #reference>
						<el-button link type="primary">删除</el-button>
					</template>
				</el-popconfirm>
			</template>
		</el-table-column>
	</el-table>
	<Pagination
		v-show="total > 0"
		:total="total"
		v-model:page="search.page"
		v-model:limit="search.pageSize"
		@pagination="initTableList"
	/>
	<!-- <el-pagination
		v-model:current-page="pageNo"
		v-model:page-size="pageSize"
		:page-sizes="[10, 20, 30, 40]"
		:background="true"
		layout="prev, pager, next, jumper,->,sizes,total"
		:total="total"
		@current-change="initTableList"
		@size-change="sizeChange"
	/> -->
	<!-- 添加角色与更新已有角色的结构:对话框 -->
	<el-dialog v-model="dialogVisite" :title="RoleParams.id ? '更新角色' : '添加角色'">
		<el-form :model="RoleParams" :rules="rules" ref="form" label-width="100px">
			<el-form-item label="角色名称" prop="roleName">
				<el-input placeholder="请你输入角色名称" v-model="RoleParams.roleName"></el-input>
			</el-form-item>
			<el-form-item label="状态" prop="active">
				<el-select v-model="RoleParams.active" placeholder="是否激活">
					<el-option label="启用" :value="1"></el-option>
					<el-option label="禁用" :value="0"></el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button type="primary" @click="dialogVisite = false">取消</el-button>
			<el-button type="primary" @click="save">确定</el-button>
		</template>
	</el-dialog>
	<!-- 抽屉组件:分配角色的菜单权限与按钮的权限 -->
	<el-drawer v-model="drawer">
		<template #header>
			<h4>分配菜单与按钮的权限</h4>
		</template>
		<template #default>
			<!-- 树形控件 -->
			<el-tree
				ref="treeRef"
				:data="menuArr"
				show-checkbox
				node-key="id"
				default-expand-all
				:props="{ children: 'children', label: 'name' }"
			/>
		</template>
		<template #footer>
			<div style="flex: auto">
				<el-button @click="drawer = false">取消</el-button>
				<el-button type="primary" @click="handler">确定</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from "vue";
//请求方法
import { reqRemoveRole, reqAllRoleList, reqAddOrUpdateRole, reqAllMenuList, reqSetPermisstion } from "@/api/role";
import type { RoleData, MenuList } from "@/api/role/type";

import type { ConfigItem } from "@/components/SearchForm/type.ts";

// 搜索框
const search = reactive({
	roleName: "",
	page: 1,
	pageSize: 10,
});
const searchConfig: ConfigItem[] = [
	{
		label: "角色名称",
		prop: "roleName",
		type: "input",
	},
];

//当前页码
let pageNo = ref<number>(1);

//存储全部已有的角色
let allRole = ref<any>([]);
//角色总个数
let total = ref<number>(0);
//控制对话框的显示与隐藏
let dialogVisite = ref<boolean>(false);
//获取form组件实例
let form = ref<any>();
//控制抽屉显示与隐藏
let drawer = ref<boolean>(false);
//收集新增岗位数据
let RoleParams = reactive<RoleData>({
	roleName: "",
	active: 1,
});
//准备一个数组:数组用于存储勾选的节点的ID(四级的)
// let selectArr = ref<number[]>([]);
//定义数组存储用户权限的数据
let menuArr = ref<MenuList>([]);
//获取tree组件实例
let treeRef = ref<any>();
//组件挂载完毕
onMounted(() => {
	//获取角色请求
	initTableList();
});
//获取全部用户信息的方法|分页器当前页码发生变化的回调
const initTableList = async () => {
	//修改当前页码
	// search.page = pager;
	let result = await reqAllRoleList(search);
	if (result.code == 200) {
		total.value = result.data.total;
		allRole.value = result.data.records;
	}
};
//搜索按钮的回调
const onSearch = () => {
	//再次发请求根据关键字
	initTableList();
};
//重置按钮的回调
const reset = () => {
	search.roleName = "";
	initTableList();
};
//添加角色按钮的回调
const addRole = () => {
	//对话框显示出来
	dialogVisite.value = true;
	//清空数据
	Object.assign(RoleParams, {
		roleName: "",
		id: 0,
	});
	//清空上一次表单校验错误结果
	nextTick(() => {
		form.value.clearValidate("roleName");
	});
};
//更新已有的角色按钮的回调
const updateRole = (row: RoleData) => {
	//显示出对话框
	dialogVisite.value = true;
	//存储已有的角色----带有ID的
	Object.assign(RoleParams, row);
	//清空上一次表单校验错误结果
	nextTick(() => {
		form.value.clearValidate("roleName");
	});
};
//自定义校验规则的回调
const validatorRoleName = (rule: any, value: any, callBack: any) => {
	if (value.trim().length >= 2) {
		callBack();
	} else {
		callBack(new Error("角色名称至少两位"));
	}
};
//角色校验规则
const rules = {
	roleName: [{ required: true, trigger: "blur", validator: validatorRoleName }],
	active: [{ required: true, trigger: "change" }],
};

//确定按钮的回调
const save = async () => {
	//表单校验结果,结果通过在发请求、结果没有通过不应该在发生请求
	await form.value.validate();
	//添加角色|更新角色的请求
	let result: any = await reqAddOrUpdateRole(RoleParams);

	if (result.code == 200) {
		//提示文字
		ElMessage({ type: "success", message: RoleParams.id ? "更新成功" : "添加成功" });
		//对话框显示
		dialogVisite.value = false;
		//再次获取全部的已有的角色
		initTableList(RoleParams.id ? pageNo.value : 1);
	}
};

//分配权限按钮的回调
//已有的角色的数据
const setPermisstion = async (row: RoleData) => {
	//抽屉显示出来
	drawer.value = true;
	//收集当前要分类权限的角色的数据
	Object.assign(RoleParams, row);
	//根据角色获取权限的数据
	let result = await reqAllMenuList(RoleParams.id as number);
	if (result.code == 200) {
		console.log(result.data.checkedKeys);
		menuArr.value = result.data.menu;
		// selectArr.value = result.data.checkedKeys;
		let checkedKeys = result.data.checkedKeys;
		checkedKeys.forEach((item: number) => {
			nextTick(() => {
				treeRef.value.setChecked(item, true, false);
			});
		});
	}
};

// const filterSelectArr = (allData: any, initArr: any) => {
// 	allData.forEach((item: any) => {
// 		if (item.select && item.level == 4) {
// 			initArr.push(item.id);
// 		}
// 		if (item.children && item.children.length > 0) {
// 			filterSelectArr(item.children, initArr);
// 		}
// 	});

// 	return initArr;
// };

//抽屉确定按钮的回调
const handler = async () => {
	//角色的ID
	const roleId = RoleParams.id as number;
	//选中节点的ID
	let arr = treeRef.value.getCheckedKeys();
	//半选的ID
	let arr1 = treeRef.value.getHalfCheckedKeys();
	let permissionIds = arr.concat(arr1);
	//下发权限
	let result: any = await reqSetPermisstion(roleId, { permissionIds });
	if (result.code == 200) {
		//抽屉关闭
		drawer.value = false;
		//提示信息
		ElMessage({ type: "success", message: "分配权限成功" });
		//页面刷新
		// window.location.reload();
	}
};

//删除已有的角色
const removeRole = async (id: number) => {
	let result = await reqRemoveRole(id);
	if (result.code == 200) {
		//提示信息
		ElMessage({ type: "success", message: "删除成功" });
		initTableList(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1);
	}
};
</script>

<style scoped></style>
